package kafka.provider;

import com.alibaba.fastjson.JSON;
import kafka.constant.TopicConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFutureCallback;

@Component
public class KafkaSender<T> {

    private static final Logger log = LoggerFactory.getLogger(KafkaSender.class);

    @Autowired(required = false)
    private KafkaTemplate<String, Object> kafkaTemplate;

    //发送消息方法
    public void send(T obj) {
        String jsonObj = JSON.toJSONString(obj);
        //发送消息
        kafkaTemplate.send(TopicConst.EXECUTOR_TOPIC, jsonObj).addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                log.info("发送失败：" + throwable.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, Object> result) {
                log.info("消息[{}]发送成功：{}",jsonObj,JSON.toJSONString(result));
            }
        });
    }
}
